package bhoost.shell;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentReceiver;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.gtalkservice.IGTalkSession;

public class Test extends Activity {
	
//	int counter = 0;
    IGTalkSession gtalkSession = null;
    EditText mUsernameField;
    EditText mTextField;
    Button mSendButton;
    String data = null;
    String lineSep = System.getProperty("line.separator");
    WebView browser;
    boolean gotMsg = false;
    XMPPConnection connection;
    private static String Host = "http://marco.lablz.com";
    Location currentLocation;
    private static final String LOCATION_UPDATE = "com.test1.Test.LOCATION_UPDATE";
    private IntentReceiver locationIntentReceiver;
    private IntentFilter locationIntentFilter;
    private boolean registered = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        JsObj jo = new JsObj(this);
        browser = new WebView(this); //(WebView)findViewById(R.id.browser);
        WebSettings ws = browser.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setJavaScriptCanOpenWindowsAutomatically(true);
        browser.addJavascriptInterface(jo, "roid");
        ws.setJavaScriptCanOpenWindowsAutomatically(true);
        ws.setSavePassword(false); // allows password input fields
        
        String zipCode = getZipCode();
        String url = "http://marco.lablz.com/register/user-login.html";
        browser.loadUrl(url);

//        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
//        currentLocation = locationManager.getCurrentLocation("gps");
//        LocationProvider lp = getProviderByName(locationManager, "gps");
//        registerReceiver(locationIntentReceiver, locationIntentFilter);
//        registered = true;
//        
//        Intent locUpdateIntent = new Intent(Test.LOCATION_UPDATE);
//        locationManager.requestUpdates(lp, 1000, 50, locUpdateIntent);
//        locationIntentFilter = new IntentFilter(LOCATION_UPDATE);
//        locationIntentReceiver = new IntentReceiver() {
//    		public void onReceiveIntent(Context context, Intent intent) {
//    			if (!registered)
//    				return;
//    			
//    			Location loc = (Location) intent.getExtra("location");
//    			
//    			currentLocation = loc;
//    			loadLocation();
//    		}        	        	
//        };
        
//        StringBuilder html = new StringBuilder();
//        try {
//        	BufferedReader br = new BufferedReader(new InputStreamReader(new URL("http://web.mit.edu/~hungry/Public/test3.html").openStream()));
//        	String line;
//        	while ((line = br.readLine()) != null) {
//        		html.append(line);
//        	}
//        } catch (IOException i) {
//        	i.printStackTrace();
//        }
//        browser.loadData(html.toString(), "text/html", "utf-8");
        
//        browser.setWebViewClient(new WebViewClient() {
//        	@Override
//        	public void onLoadResource(WebView webView, String url) {
//                GetMethod method;
//                HttpMethodParams httpMethodParams;
//                HttpClient httpClient;
//                int statusCode;
//                byte[] responseBody;
//               
//                method = null;
//                try {
//                    httpClient = new HttpClient();
//                    httpClient.getHostConfiguration().setHost(Test.Host);
//
//                    method = new GetMethod(url);
//                    httpMethodParams = method.getParams();
//                    httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));
//                    httpMethodParams.setParameter("param1", "13455");
//                    method.setParams(httpMethodParams);
//                    statusCode = httpClient.executeMethod(method);
//
//                    if (statusCode != HttpStatus.SC_OK) {
//                        webView.loadData(new String("statusCode = " + statusCode),"text/html", "utf-8");
//                        return;
//                    }
//
//                    responseBody = method.getResponseBody();
//                    String returnStr = new String(responseBody);
//                    webView.loadData(returnStr, "text/html", "utf-8");
//                } catch (Exception e) {
//                    webView.loadData("<input type=\"button\" value=\"Exception: \" />" + e.toString(),"text/html", "utf-8");
//                    Log.i("AndroidTest1.Test", e.toString(), e);
//                } finally {
//                    if(method != null){
//                        method.releaseConnection();
//                    }
//                }        		
//        	}
//        });

//        browser.setWebChromeClient(new WebChromeClient());
//        browser.loadData("<html><body><a href=\"#\" onClick=\"alert('Surprise')\">Yo there</a></body></html>", "text/html", "utf-8");
        
//        loadTimerJavascript();
//        loadOnClickJavascript();
//        loadLocation();
        
        setContentView(browser);
    }
    
    private String getZipCode() {        
    	String zipCode = null;
    	String name = null;
    	String startCodeTag = "<postalcode>";
  		String endCodeTag = "</postalcode>";
  		String startNameTag = "<name>";
  		String endNameTag = "</name>";
    	try {
    		String urlString = "http://ws.geonames.org/findNearbyPostalCodes?lat=" + currentLocation.getLatitude() + "&lng=" + currentLocation.getLongitude();
    		URL url = new URL(urlString);
	    	BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
	    	String line;
	    	String xml = "";
	    	while ((line = in.readLine()) != null) {
	    		xml += line + lineSep;
	    	}
    		if (xml.contains(startCodeTag)) {
    			int startCodeIndex = xml.indexOf(startCodeTag) + startCodeTag.length();
    			int endCodeIndex = xml.indexOf(endCodeTag);
    			int startNameIndex = xml.indexOf(startNameTag) + startNameTag.length();
    			int endNameIndex = xml.indexOf(endNameTag);
    			zipCode = (startCodeIndex == -1 || endCodeIndex == -1) ? null : xml.substring(startCodeIndex, endCodeIndex);
    			name = (startNameIndex == -1 || endNameIndex == -1) ? null : xml.substring(startNameIndex, endNameIndex);
    		}
    	} catch (IOException i) {
    		i.printStackTrace();
    	}
    	
//        browser.loadData("<html><head><title>JS calls Android Method</title></head><body>" +
//        		"Lat: " + currentLocation.getLatitude() + lineSep +
//        		"Lon: " + currentLocation.getLongitude() + lineSep +
//        		"Closest zip code: " + ((zipCode != null) ? zipCode : "Couldn't find closest zip code") + lineSep +
//        		((name != null) ? "This zip code represents the city of: " + name : "") +
//        		"</body></html>", "text/html", "utf-8");
    	
    	return zipCode;
    }
    
    private void loadOnClickJavascript() {
        browser.loadData("<html><head><title>JS calls Android Method</title></head><body>" +
                "<script>" +
              			"function getTheaters() {" +
              			"roid.doStuff(\"\",\"\",document.SampleForm.recipient.value, document.SampleForm.message.value);" +
              			"}" +
              	"</script>" +
              	"<form name=\"SampleForm\">" +
              	"<input name=\"recipient\" type=\"text\" cols=\"20\">Recipient</input>" +
              	"<input name=\"message\" type=\"text\" cols=\"20\">Message</input>" +
              	"<button onClick=\"getTheaters()\">Send Message</button>" +
              	"</form>" +
//              	((data!=null) ? data : "") + 
              	"</body></html>", "text/html", "utf-8");    	
	}

	private void loadTimerJavascript() {
        browser.loadData("<html><head><title>JS calls Android Method</title></head><body>" +
                "<script>t = 5000;" +
              			"function startTimer(){" +
              			"setInterval(\"print()\" , t)" +
              			"}" +
              			"function print() {" +
              			"roid.doStuff(\"\",\"\",\"\",\"\");" +
              			"}" +
              			"startTimer();" +
              	"</script>" +
              	"<form name=\"SampleForm\">" +
              	"<input name=\"input1\" type=\"text\" cols=\"20\"></input>" +
        		"</form>" +
              	"</body></html>", "text/html", "utf-8");        
    }
    
	private void sendMessage(String username, String password, String recipient, String text) {
		ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
		connection = new XMPPConnection(config);
		try {
			connection.connect();
			connection.login(uname, pwd);
		} catch (XMPPException x) {
			x.printStackTrace();
		}
		PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
	    connection.addPacketListener(new PacketListener() {  
	    	public void processPacket(Packet packet) {  
	    		Message message = (Message) packet;  
	    		if (message.getBody() != null) {  
	    			String fromName = StringUtils.parseBareAddress(message.getFrom());
//	    			String msgText = message.getBody();
//	    			Log.i("message text", msgText);	    			
//	    			System.out.println("from: " + fromName + ", body: " + message.getBody());
	    			sendMessage(uname, pwd, uname, "re: " + message.getBody());
	    			gotMessage();
	    		}  
	    	}  
	    }, filter);  		    
	    
	    Message message = new Message();
	    message.setTo(recipient + "@gmail.com");
//	    message.setSubject("this is a test");
	    message.setBody(text);
	    message.setType(Message.Type.chat);
	    connection.sendPacket(message);
	}
	
	public void gotMessage() {
		gotMsg = true;
	}
	
	private LocationProvider getProviderByName(LocationManager locationManager, String name) {
		LocationProvider provider = null;
		for (LocationProvider p : locationManager.getProviders()) {
			if (p.getName().equalsIgnoreCase(name)) {
				provider = p;
			}
		}

		return provider;
	}

	
//    @Override
//    public void onResume() {
//         super.onResume();         
//         registerReceiver(locationIntentReceiver, locationIntentFilter);
//         registered = true;
//    }
    
    /**
     * Make sure to stop the animation when we're no longer on screen,
     * failing to do so will cause a lot of unnecessary cpu-usage!
     */
//    @Override
//    public void onFreeze(Bundle icicle) {
//         this.unregisterReceiver(locationIntentReceiver);
//         registered = false;
//         super.onFreeze(icicle);
//    }	
	
    class JsObj {
    	  private Context con;
    	  boolean flashing = false;
    	  
    	  public JsObj(Context con) {
    	    this.con = con;
    	  }
    	 
    	  public String doStuff(String username, String password, String recipient, String text) throws DeadObjectException {
//    		  Toast.makeText(con, "This is a notification, pay attention", Toast.LENGTH_SHORT).show();
//    		  Notification n = new Notification(con, R.id.iconandtext, "Look over here!", 0, null, null, null, R.id.iconandtext, null, null);
//    		  n.lights = true;
//    		  NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//    		  nm.cancel(R.id.iconandtext);
//    		  nm.notify(R.id.iconandtext, n);

    		  // vibrate
//    		  android.os.Vibrator myVibrator = new android.os.Vibrator();         
//    		  myVibrator.vibrate(new long[] {200, 1000, 200, 1000}, 2);

//    		  MovieScrapingTest test = new MovieScrapingTest(input);
//    		  MovieScrapingTest.MovieTheater[] theaters = test.getTheaters();
//    		  StringBuffer sb = new StringBuffer();
//    		  for (MovieScrapingTest.MovieTheater theater: theaters) {
//    			  sb.append(theater.name);
//    			  sb.append(lineSep);
//    		  }
//    		  data = sb.toString();
//    		  loadOnClickJavascript();

    		  sendMessage(username, password, recipient, text);
    		  loadOnClickJavascript();
    		  // flash screen
//    		  if (!flashing) {
//    			  Intent flash = new Intent((Test)con, FlashScreen.class);
//    			  startSubActivity(flash, 1);
//    			  
//				  flashing = true;
//    		  } else {
//    			  flashing = false;
//    		  }
//
    		  
//	          counter++;    		  
    		  return "message sent";// + counter;
    	  }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
	final String uname = "mvayngrib";
	final String pwd = "xyc157";
}